package com.duke.payphone.acct;

import java.io.Serializable;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.duke.payphone.Global;
import com.duke.payphone.LoginActivity;
import com.duke.payphone.R;
import com.duke.payphone.ServerPortal;
import com.duke.payphone.factory.MapFactory;


/**
 * edit old account, this activity is called by the ROOT
 * 
 * activity will populate textedit fields with information that is currently
 * true
 * user can edit these fields
 * 
 * press save:
 * It needs to check the validity of the information.
 * Then it sends it to the server.. another check.. server could respond = not
 * valid.
 * ex. user name taken, password taken... no repeats
 * 
 * if valid, toast = "account info saved", stay at this screen
 * 
 * if not valid, toast = "NOT saved", stay at this screen
 * 
 * 
 * Buttons: Save, Back (back to the ROOT)
 * 
 * @author Michael
 * 
 */
public class AccountEditActivity extends Activity {

    private Global globalvars;

    private EditText user;
    private EditText pswd;
    private EditText fn;
    private EditText ln;

    private String userStr;
    private String pswdStr;
    private String fnStr;
    private String lnStr;

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_edit);

        globalvars = (Global) getApplicationContext();

        user = (EditText) findViewById(R.id.et_user);
        pswd = (EditText) findViewById(R.id.et_pswd);
        fn = (EditText) findViewById(R.id.et_fn);
        ln = (EditText) findViewById(R.id.et_ln);

        executeGetUser();
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu) {
        // getMenuInflater().inflate(R.menu.activity_account_edit, menu);
        // return true;
        return false;
    }

    /**
     * retrieves data for a user
     */
    private void executeGetUser () {

        // set up the request map
        Map<String, Serializable> request = MapFactory.createTransmitMap("getuser");

        if (true) {
            // send to server
            Map<String, Serializable> response = ServerPortal.contactServer(request);

            // wait for reply
            if (response.containsKey("server") && response.get("server").equals("valid")) {

                if (response.containsKey("session") && response.get("session").equals("valid")) {

                    if (response.containsKey("result") && response.get("result").equals("valid")) {
                        onGetUserValid(response);
                    }
                    else {
                        onGetUserInvalid(response);
                    }
                }
                else {
                    onSessionInvalid();
                }
            }
            else {
                onServerInvalid();
            }
        }
    }

    /**
     * @param response
     */
    private void onGetUserValid (Map<String, Serializable> response) {

        // populate the fields
        if (response.containsKey("username")) {
            user.setText((String) response.get("username"));
        }
        if (response.containsKey("password")) {
            pswd.setText((String) response.get("password"), TextView.BufferType.EDITABLE);
        }
        if (response.containsKey("firstname")) {
            fn.setText((String) response.get("firstname"), TextView.BufferType.EDITABLE);
        }
        if (response.containsKey("lastname")) {
            ln.setText((String) response.get("lastname"), TextView.BufferType.EDITABLE);
        }
    }

    /**
     * @param response
     */
    private void onGetUserInvalid (Map<String, Serializable> response) {
        Toast.makeText(globalvars, "Error retrieving user information.", Toast.LENGTH_SHORT).show();
        finish();
    }

    public void executeBack (View v) {
        finish();
    }

    public void executeUpdate (View v) {
        updateData();

        // check validity
        if (checkData()) {

            // send to server
            Map<String, Serializable> response = ServerPortal.contactServer(prepareTransmitMap());

            // wait for reply
            if (response.containsKey("server") && response.get("server").equals("valid")) {

                if (response.containsKey("session") && response.get("session").equals("valid")) {

                    if (response.containsKey("result") && response.get("result").equals("valid")) {
                        onEditUserValid(response);
                    }
                    else {
                        onEditUserInvalid(response); // should not happen
                    }
                }
                else {
                    onSessionInvalid();
                }
            }
            else {
                onServerInvalid();
            }
        }

    }

    /**
     * Rereads the data from text fields
     */
    private void updateData () {
        userStr = user.getText().toString();
        pswdStr = pswd.getText().toString();
        fnStr = fn.getText().toString();
        lnStr = ln.getText().toString();
    }

    /**
     * returns a map
     * 
     * @return
     */
    private Map<String, Serializable> prepareTransmitMap () {
        Map<String, Serializable> request = MapFactory.createTransmitMap("edituser");
        request.put("username", userStr);
        request.put("password", pswdStr);
        request.put("firstname", fnStr);
        request.put("lastname", lnStr);
        return request;
    }

    private boolean checkData () {
        // verify data is correct
        if (userStr.isEmpty() || pswdStr.isEmpty() || fnStr.isEmpty() || lnStr.isEmpty()) {
            // if incorrect, toast: [how to correct the data]
            Toast.makeText(globalvars, "All fields are required.", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    /**
     * @param response
     */
    private void onEditUserValid (Map<String, Serializable> response) {
        Toast.makeText(globalvars, "Account update successful.", Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * Note: this should never happen
     * 
     * @param response
     */
    private void onEditUserInvalid (Map<String, Serializable> response) {
        Toast.makeText(globalvars, "Account update unsuccessful. Please try again.",
                       Toast.LENGTH_SHORT).show();
    }

    /**
     * If server has timed out
     */
    private void onServerInvalid () {
        // toast: server error, please verify server connection and retry
        Toast.makeText(globalvars, "Server/network error. Please retry.", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * If session has timed out
     */
    private void onSessionInvalid () {
        // reset the sessionID to null
        Global.sessionid = "";

        // toast: current session has timed out
        Toast.makeText(globalvars, "Current session has timed out.", Toast.LENGTH_SHORT).show();

        // go back to the login screen
        Intent toLogin = new Intent(this, LoginActivity.class);
        toLogin.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(toLogin);
        finish();
    }

}
